import Mock from 'mockjs'
import menu from '@/mock/json/menu.json'
import books from "@/mock/json/books.json"
import hotBooks from "@/mock/json/hotBooks.json"
import address from "@/mock/json/address.json"


// --------------------------- layout -------------------------
Mock.mock('/home/category/head','get', ()=>{
  return {
    "code": "200",
    "msg": "ok",
    "result": menu
  }

})

// ---------------------- home ------------------------

Mock.mock('/home/hot','get', ()=>{

  return {
    "code": "200",
    "msg": "ok",
    "result": hotBooks
  }

})

Mock.mock('/home/books','get', ()=>{


  return {
    "code": "200",
    "msg": "ok",
    "result": books
  }

})
//RegExp("/getinfo" + ".*")
const  getParamsId = (options,property) => {
  const urlParts = options.url.split('?')
  let values = null
  if (urlParts.length > 1) {
    const queryParams = urlParts[1].split('&')
    queryParams.forEach(param => {
      const [key, value] = param.split('=')
      if (key === property) {
        values = value
      }
    })
  }
  return values
}

Mock.mock(RegExp("/home/bookDetail?" + ".*"),'get', (options)=>{
  const id = getParamsId(options,'id')

  const filteredBook = books.find(book => book.id === Number(id));
  return {
    "code": "200",
    "msg": "ok",
    "result": filteredBook
  }

})

//category list

Mock.mock(RegExp("/category?" + ".*"),'get', (options)=>{
  const id = getParamsId(options,'id')
  const filteredBook = books.filter(book => book.type === Number(id));
  return {
    "code": "200",
    "msg": "ok",
    "result": filteredBook
  }

})

//TODO search
Mock.mock('/home/search','get', (options)=>{
  const urlParts = options.url.split('?')
  let id = null
  if (urlParts.length > 1) {
    const queryParams = urlParts[1].split('&')
    queryParams.forEach(param => {
      const [key, value] = param.split('=')
      if (key === 'keyword'){}
    })
  }
})

// -------------------------------------------- order ----------------------------
//订单存储
const orders = []

import { useCartStore } from '@/stores/cartStore'
Mock.mock('/member/order/pre','get', ()=>{

  //localstorage中获取数据
  const cartString = localStorage.getItem('cart');
  const cartObj = JSON.parse(cartString) || [];
  cartObj.cartList = cartObj.cartList.filter(item => item.selected)

  const cartStore = useCartStore()

  cartObj.userAddresses = address
  const allPrice = cartObj.cartList.reduce((pre, item) => pre + item.price * item.count, 0)

  cartObj.summary = {
    postFee: allPrice >= 68 ? 0 : 5,
    totalPayPrice: allPrice >= 68 ? allPrice: + allPrice+5,
    totalPrice: allPrice,
    goodsCount: cartObj.cartList.reduce((pre, item) => pre + item.count, 0)
  }

  return {
    "code": "200",
    "msg": "ok",
    "result": cartObj
  }

})

Mock.mock('/order/create','post', (options)=>{
  const orderId = Math.floor(10000000 + Math.random() * 90000000);

  //localStorage
  localStorage.setItem(orderId,options.body)

  return {
    "code": "200",
    "msg": "ok",
    "result": {
      "orderId": orderId
    }
  }

})

//获取订单信息
Mock.mock(RegExp("/member/order?" + ".*"), 'get', (options) => {
  const orderId = getParamsId(options,'id');

  if (!orderId) {
    return {
      "code": "400",
      "msg": "Invalid or missing orderId",
      "result": null
    };
  }

  const orderString = localStorage.getItem(orderId);

  if (!orderString) {
    return {
      "code": "404",
      "msg": "Order not found",
      "result": null
    };
  }

  let orderObj;
  try {
    orderObj = JSON.parse(orderString) || {};
  } catch (error) {
    console.error("Failed to parse orderString:", error);
    return {
      "code": "500",
      "msg": "Internal server error",
      "result": null
    };
  }

  return {
    "code": "200",
    "msg": "ok",
    "result": orderObj
  };
});


//查询
Mock.mock("/home/search",'post', (options)=>{
  const {keyword} = JSON.parse(options.body)
  const filteredBook = books.filter(book =>
    book.title.toLowerCase().includes(keyword.toLowerCase())
  );
  return {
    "code": "200",
    "msg": "ok",
    "result": filteredBook
  }

})

